<template>
  <scroll-view
    enable-back-to-top
    scroll-y
    class="customer"
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="getCorpusData"
  >
    <u-navbar leftIcon="" bgColor="#3775cb" :placeholder="true" :safeAreaInsetTop="false">
      <template #center>
        <u-search
          placeholder="关键词搜索"
          v-model="queryParams.question"
          @search="handleQuery"
          @custom="handleQuery"
          margin="20rpx"
          :actionStyle="{
            color: '#ffffff',
          }"
        ></u-search>
      </template>
    </u-navbar>

    <u-cell-group :border="false">
      <u-cell
        v-for="(row, index) in corpusList"
        :key="index"
        :title="row?.question"
        :label="row?.answer"
      >
        <template #right-icon>
          <u-icon
            v-copyText="row?.answer"
            v-copyText:callback="copyTextSuccess"
            @click="sendChatMessage(row)"
            name="email"
            color="#2979ff"
            size="28"
          ></u-icon>
        </template>
      </u-cell>
    </u-cell-group>
    <u-empty v-show="isFinish && corpusList.length === 0" mode="history" />
    <u-loadmore v-if="isLoading" status="loading" />
    <u-loadmore v-if="isFinish && corpusList.length > 0" status="nomore" />
    <cus-picker ref="cusPicker" @change="clickUserProfile" />
  </scroll-view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getCorpusListAPI } from '@/services/corpus'
import * as ww from '@wecom/jssdk'
import { createJsapiSignatureAPI } from '@/services/common'
import CusPicker from '@/components/customer/cus-picker.vue'
import { onShow } from '@dcloudio/uni-app'
import { getContextApi, registerApi } from '@/utils/wecom'

const cusPicker = ref<InstanceType<typeof CusPicker>>()
// 请求参数
const queryParams: Required<any> = {
  question: undefined,
  pageNum: 1,
  pageSize: 10,
}

const qwEntry = ref<string>('')
const isFinish = ref(false)
// 是否触发下拉刷新
const isTriggered = ref(false)
// 获取订单列表
const corpusList = ref<any[]>([])
// 是否加载中标记，用于防止滚动触底触发多次请求
const isLoading = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 重置数据
  queryParams.pageNum = 1
  corpusList.value = []
  isFinish.value = false
  // 加载数据
  await getCorpusData()
  // 关闭动画
  isTriggered.value = false
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  corpusList.value = []
  isFinish.value = false
  getCorpusData()
}

const getCorpusData = async () => {
  // 如果数据出于加载中，退出函数
  if (isLoading.value) return
  // 退出分页判断
  if (isFinish.value === true) {
    return
  }
  // 发送请求前，标记为加载中
  isLoading.value = true
  // 发送请求
  const res = await getCorpusListAPI(queryParams)
  // 发送请求后，重置标记
  isLoading.value = false
  // 数组追加
  corpusList.value.push(...res.rows)
  // 分页条件
  if (corpusList.value.length < res.total) {
    // 页码累加
    queryParams.pageNum++
  } else {
    // 分页已结束
    isFinish.value = true
  }
}
const clickUserProfile = async (row: any) => {
  ww.openUserProfile({
    type: 2,
    userid: row.qwExternalUserid,
  })
}
/** 复制成功 */
const copyTextSuccess = () => {
  uni.showToast({
    icon: 'none',
    title: '复制成功，发送客户',
  })
}

const sendChatMessage = async (row: any) => {
  if (qwEntry.value.includes('chat_')) {
    ww.sendChatMessage({
      msgtype: 'text',
      text: {
        content: row?.answer,
      },
    })
  } else {
    cusPicker.value!.open()
  }
}
onShow(async () => {
  await registerApi(['sendChatMessage', 'getContext', 'openUserProfile'])
  qwEntry.value = await getContextApi()
})

onMounted(async () => {
  getCorpusData()
})
</script>

<style scoped lang="scss"></style>
